import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, message, Modal, Form, Button, Input, Popconfirm } from 'antd';
import { filterAuth } from '@/support/common';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { FormInstance } from 'antd/lib/form';
import Ellipsis from '@/components/Ellipsis';
import * as G from '@/utils/common';
import moment from 'moment';
import { downloadUrl } from '@/utils/utils'

const FormItem = Form.Item;
const mapStateToProps = (state:any) => ({
  sgwLogUpload: state.sgwLogUpload,
  loading: state.loading.models["sgwLogUpload"],
});
class SgwLogUpload extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      modalVisible: false,
      formData: {},
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'sgwLogUpload/getFetchPage',
      payload: { url: '/feedback/sgwUpload/task/getPage' },
    });
  }

  //  查询参数校验
  dataFormat = (fields: any) => {
    if (G.isNotEmptyAndNil(fields['handleTimeRange'])) {
      const [start, end] = fields.handleTimeRange;
      fields['startDate'] = moment(start).local().format('YYYY-MM-DD');
      fields['endDate'] = moment(end).local().format('YYYY-MM-DD');
    }
    delete fields['handleTimeRange'];
    return fields;
  }

  //  查询参数重置
  handleFormReset = (fields: any) => {
    this.searchForm.current?.resetFields();
    this.setState({
      formValues: {}
    })
  }

  //  获取日志弹框
  handleUpload = (val: any) => {
    this.setState({ modalVisible: true, formData: {} });
  }


  //  发起主动上传日志任务
  handleSubmit = () => {
    this.formRef.current?.submit();
  }

  ok = (vals: any) => {
    const { dispatch } = this.props;
    const data = {
      vin: vals?.vin || '',
    }
    dispatch({
      type: 'sgwLogUpload/postData',
      payload: {
        url: '/feedback/sgwUpload/upload',
        ...data
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.handleClose();
          message.success('操作成功');
          this.handleFreshPage();
        }
      }
    })
  }

  //  刷新table数据
  handleFreshPage = () => {
    const { dispatch } = this.props;
    this.searchForm.current?.resetFields();
    dispatch({
      type: 'sgwLogUpload/getFetchPage',
      payload: { url: '/feedback/sgwUpload/task/getPage' },
    });
  }


  handleClose = () => {
    this.setState({ modalVisible: false });
    this.formRef.current?.resetFields();
  }


  render () {
    const { sgwLogUpload: {
      pageData: { list, pagination },
    }, loading, location: { pathname = '/' } } = this.props;
    const { formValues, modalVisible, formData } = this.state;
    const page = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      total: pagination.total,
    }
    const searchItems = [
      {
        type: 'input',
        title: 'VIN',
        key: 'vin',
        customStyle: 7,
      },
      {
        title: '上传时间',
        type: 'rangePicker',
        format: 'YYYY-MM-DD',
        key: 'handleTimeRange',
        customStyle: 9,
        // customStyle: 10,
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...page,
      showTotal: () => (
        <span>共&nbsp;{page?.total}&nbsp;条</span>
      ),
    };

    const columns = [
      {
        title: '序号',
        dataIndex: 'no',
        width: 60,
        render: (text: any, record: any, index: any) => {
          return index + 1 + (page.current - 1) * page.pageSize;
        },
      },
      {
        title: 'VIN',
        dataIndex: 'vin',
      },
      {
        title: 'PDSN',
        dataIndex: 'pdsn',
      },
      {
        title: '上传时间',
        dataIndex: 'uploadTime',
        render:(text: any)=>{
          return  moment(text).format('YYYY-MM-DD HH:mm:ss');
        }
      },
      {
        title: '文件名称',
        dataIndex: 'fileName',
        render: (text: string) => (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 80,
        fixed: 'right',
        render: (text: any, record: any) => {
          // render: (text: any) => <a target="_blank" href={text} title="点击下载模板文件">模板文件下载</a>
          const btns: any[] = [];
          if (record.fileUrl) {
            btns.push({
              title: '下载文件',
              key: 'download',
              auth: 'sgwLogUpload_show',
              onConfirm: () => {
                downloadUrl(record.fileUrl);
              },
            })
          }
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        }
      }

    ]

    const tableProps = {
      columns,
      dataSource: list || [],
      loading,
      rowKey: (record: any) => record.id,
      pagination: paginationProps,
      scroll: { x: 'max-content' }
    };

    const footer = (
      <div>
        <Button size="small" onClick={this.handleClose}>
          取消
        </Button>
        <Button size="small" loading={loading} onClick={this.handleSubmit} type="primary">
          保存
        </Button>
      </div>
    );

    
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'sgwLogUpload/getFetchPage',
              url: '/feedback/sgwUpload/task/getPage',
              extraArgs: {},
            }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
            handleFieldsValue={this.dataFormat}
          />
        </Card>
        <Card
          style={{ marginTop: 12 }}
          bordered={false}
        >
          {/* {filterAuth('contentItem_doAdd', permissions, pathname) ? (
            <div className="my_newItem">
              <Button size="small" icon={<PlusOutlined />} type="primary" onClick={this.handleAdd}>
                新增
              </Button>
            </div>
          ) : null} */}
          <div style={{}}>
              <Button size="small" type="primary" onClick={this.handleUpload}>
                获取日志
              </Button>
            </div>
          <PateoTable
            extraHandle={true}
            currentName = 'page'
            pageSizeName='size'
            tableProps={tableProps}
            fetchParams={{ type: 'sgwLogUpload/getFetchPage', url: '/feedback/sgwUpload/task/getPage' }}
            formValues={formValues}
          />
        </Card>
        <Modal
          style={{ top: '10%' }}
          width={450}
          footer={footer}
          title="获取日志"
          visible={modalVisible}
          onCancel={this.handleClose}
        >
          <Form style={{ marginTop: 12 }} ref={this.formRef} onFinish={this.ok} layout="vertical">
            <FormItem
              label=""
              name="vin"
              rules={[]}
            >
              <Input maxLength={20} placeholder="请输入" />
            </FormItem>
          </Form>
        </Modal>

      </div>
    )
  }
}
export default connect(mapStateToProps)(SgwLogUpload);
